<template>
    <div class="meterialManagement">
        <header-btn style="margin-bottom:10px"  :btnList='tabArr' :tabIndex='curTabIndex' @changetabIndex='getCurTabIndexFn'>
             <el-select @change='changeWarehouse' style="width:150px;margin:17px 10px 0 0" size='medium'  v-model="form.wh_id" placeholder="请选择" >
                <el-option   v-for="item in myWarehouse"  :key="item.wh_id"  :label="item.wh_name" :value="item.wh_id"></el-option>
            </el-select>
        </header-btn>
        <!-- 搜索框和列表 -->
        <div class="operationBox" v-if="indexList.indexOf(curTabIndex)>-1&&(action=='table')">
                <!-- 搜索框 -->
                <searchBox ref="searchBox" v-if='[0,3].indexOf(curTabIndex)>-1' :formInline='formInline' :form='form' @search="onSubmit"></searchBox>
                <!-- 列表 -->
                <div class="tabel_box">
                    <lpj-table-vue :baseNum='paginationMes.per_page*(paginationMes.current_page-1)' ref="lpjTable" :tableData="tableData" :tableHeaderData="tableHeaderData[indexList.indexOf(curTabIndex)]" @linkBtnFn="linkBtnFn" @pointerClick="pointerClick" @handleSelectionChange="handleSelectionChange"></lpj-table-vue>
                </div>
                <!-- 页码 -->
                <pagination v-if="paginationMes.total&&paginationMes.total>10" align="right" :paginationMes="paginationMes" @sizeChangeFn="sizeChangeFn" @currentChangeFn="currentChangeFn"></pagination>
            
        </div>
        <!-- 新增耗材 -->
        <Add-dailog  ref="formVueBox" v-if="curTabIndex==2"/>
        <!-- 耗材分类 -->
        <Meterial-class  v-if="curTabIndex==1" />
         <dialog-vue :dialogTitle="dialogTitle" :dialogVisible="dialogVisible" @dialogVisibleChangeFn="dialogVisibleChangeFn" :ruleForm="ruleForm"  @goCancel="goCancel"  @goSubmit="goSubmit">
        </dialog-vue>
        <confirm-dialog @goConfirm='goConfirm' ref="confirmDialog"></confirm-dialog>
    </div>
</template>

<script>
 /* eslint-disable */ 
import fileutil from '@/libs/fileUtil'
import TabVue from "@/components/TabVue"
import Pagination from "@/components/Pagination"
import LpjTableVue from "@/components/LpjTableVue"
import DialogVue from "@/components/DialogVue"
import constObj from '@/config/const' /**表头常数 */
import AddDailog from "./components/AddDailog"/**新增耗材 */
import MeterialClass from "./components/MeterialClass"/**耗材分类 */
import headerBtn from "@/components/headerBtn"/**表头tab */
import searchBox from "@/components/searchBox"/**搜索框 */
import confirmDialog from "@/components/confirmDialog"/**确认领用、报失、退还弹窗 */
/**     耗材列表页          耗材领用查询    库存预警查询              耗材上下架       耗材补充数量  耗材确认发放*/
import {getConsumablesList,geReceiveQuery,getInventoryWarningQuery,showConsumables,addStock,confirmConsumable,getConsumableNumber} from './api'
import {getCategoriesApi,} from "@/api" 

export default {
    name:"meterialManagement",
    components:{TabVue,LpjTableVue,Pagination, DialogVue,headerBtn,searchBox,MeterialClass,AddDailog,confirmDialog},
    data(){
        return { 
            myWarehouse:[],
            form:{ c_name:'',time:[], c_code:'', c_cid:'', is_show:'',users:'',departments:'',wh_id:''},/**搜索框form */
            formInline:[ /**搜索框 */
                {type:'input',value:'c_name',label:'耗材名称：',placeholder:'请输入',hide:false},
                {type:'input',value:'c_code',label:'耗材编码：',placeholder:'请输入',hide:false},
                {type:'select',value:'c_cid',label:'耗材分类：',placeholder:'请输入',options:[],hasGroup:true,defaultProp:['id','category_name','cate'],hide:false},
                {type:'select',value:'is_show',label:'耗材状态：',placeholder:'请选择',options:[{id:1,name:'上架'},{id:2,name:'下架'},],hasGroup:false,defaultProp:['id','name'],hide:false},
                {type:'dept',value:'departments',label:'领用部门：',placeholder:'请选择',options:[],hasGroup:false,defaultProp:['id','name'],hide:true},
                {type:'daterange',value:'time',label:'入库时间：',hide:false},
                {type:'people',value:'users',label:'领用人：',placeholder:'请输入',options:[],hide:true}
            ],
            action:'table',/**table 为表格，add为新增页面 */
            ruleForm: {
                formList: [],
            },/*消息框表单*/
            rules: {},/*表单校验规则*/
            tabArr: [
               {num: '',content:'耗材列表'},
			   {num: '',content:'耗材分类'},
			   {num: '',content:'新增耗材'},
			   {num: '',content:'领用申请'},
			   {num: '',content:'库存预警'}
			],
            /*当前选中的 tab下标*/
            curTabIndex:0,
            /**操作列表表头数据 */
            tableHeaderData:JSON.parse(JSON.stringify(constObj.tableHeaderOfMeterialManager)) ,
            indexList:[0,3,4],
            /*操作列表table里的数据 */
            tableData:[],
            /*分页 数据*/
            paginationMes:{per_page:10,current_page:1,totol:0}, /**操作列表分页参数 */
            selectionData:[],  /** 表格CheckBox选中数据 */
            dialogVisible:false,
            dialogTitle:'补充数量',
            ruleForm: {
                formList: [],
                addForm:[]
            },/*领用表单*/
            userArr:[],
            deptArr:[],
            
        }
    },
    created(){
        this.curTabIndex = localStorage.curTabIndex?Number(localStorage.curTabIndex):0
        this.myWarehouse = this.$store.state.myWarehouse
        this.form.wh_id = this.$store.state.warehouseOfAssetsManager||this.$store.state.myWarehouse[0].wh_id
        log(this.myWarehouse,this.form.wh_id )
        this.$store.commit('changeWarehouse',this.form.wh_id);
        /**获取耗材操作列表 */
        this.getCurTabIndexFn(this.curTabIndex)
    },
    mounted() {
      this.getConsumable()
    },
    methods:{
         dialogVisibleChangeFn(val){
            this.dialogVisible = val
            if(!val){
                this.ruleForm.formList=[]
            }
        },
        // /*监听资产领用弹窗点击确定*/
        goSubmit(e){
            addStock(e).then((res)=>{
                this.goCancel()
                this.$store.commit('changeDisabled', false)
                this.getCurTabIndexFn(this.curTabIndex)
            }).catch(err=>{
                this.$store.commit('changeDisabled', false)
            })
        },
        /**弹窗取消按钮 */
        goCancel(){
            this.dialogVisible = false
            this.ruleForm = {formList:[],addForm:[]}
        },
        /**当仓库值改变时，缓存起来,并刷新模块内数据 */
        changeWarehouse(val){
            this.$store.commit('changeWarehouse',val);
            if(this.curTabIndex==1){ /**耗材分类 */
                this.$refs.ConsumablesClass.getData()
            }else if(this.curTabIndex==2){ /**新增耗材 */
                this.$refs.formVueBox.getClassData()
            } else{
                this.messageSearch()
            }
        },
        /**查询 */
        onSubmit(form,user,dept) {
            this.userArr = user
            this.deptArr = dept
            this.paginationMes.current_page = 1
            this.messageSearch()
        },
        /**tab组件点击事件 */
        getCurTabIndexFn(val){
            
            /**初始化数据 */
            localStorage.curTabIndex = val
            this.curTabIndex = val
            this.paginationMes = {per_page:10,current_page:1,totol:0}
            

            /**初始化搜索框和搜索框相关的数据 */
            this.form = { c_name:'',time:[], c_code:'', c_cid:'', is_show:'',users:'',departments:'',wh_id:this.$store.state.warehouseOfAssetsManager,}/**搜索框form */
            this.userArr = []
            this.deptArr = []
            this.$refs.searchBox?this.$refs.searchBox.init():''

            if(this.indexList.indexOf(val)>-1){/*如果是列表页 */
                if(val==0){
                    this.formInline[6].hide = true;this.formInline[4].hide = true;this.formInline[3].hide = false; /**耗材列表需要隐藏搜索框的操作人 */
                } 
                if(val==3) {
                    this.formInline[4].hide = false;this.formInline[6].hide = false;this.formInline[3].hide = true; /**领用记录需要显示搜索框的操作人 */
                }
                this.messageSearch()
                val!=4?this.getAllClass():''
            }
        },
        /**获取耗材分类 */
        getAllClass(){
            getCategoriesApi({category_type:1,wh_id:this.form.wh_id}).then(res=>{
                this.formInline[2].options = res
            })
        },
        /**获取列表 */
        messageSearch(){
            let goSearchParam = {
                page:this.paginationMes.current_page,
                num:this.paginationMes.per_page,
                c_name:this.form.c_name,
                c_code:this.form.c_code,
                c_cid:this.form.c_cid,
                wh_id:this.form.wh_id,
                start_time:this.form.time&&this.form.time.length?this.form.time[0]:'',
                end_time:this.form.time&&this.form.time.length?this.form.time[1]:'',
            }
            let promise
            switch(this.curTabIndex){
                case 0:goSearchParam.is_show=this.form.is_show;promise=getConsumablesList(goSearchParam);break;/**耗材列表页 */
                case 3:goSearchParam.users=this.userArr&&this.userArr.length?JSON.stringify(this.userArr):'';goSearchParam.departments=this.deptArr&&this.deptArr.length?JSON.stringify(this.deptArr):'';promise=geReceiveQuery(goSearchParam);break;/**领用记录列表页 */
                case 4:promise=getInventoryWarningQuery({page:this.paginationMes.current_page,num:this.paginationMes.per_page,wh_id:this.form.wh_id,});break;/**回收站列表页 */
            }
            promise?promise.then(res=>{
                this.paginationMes={total:Number(res.total),per_page:Number(res.per_page),current_page:Number(res.current_page),}
                this.tableData=res.data
            }).catch(err=>{
                this.tableData=[]
            }):''
        },
        /**操作列按钮 */
        linkBtnFn(val,data){
            switch (val) {
                case "编辑":this.$router.push({ name:'editMeterial',query:{id:data.id}});break;
                case "下架":this.toDeleteFn(data,'确认要下架这款耗材吗？下架后前台页面将不再显示，数据不会删除，员工无法在前台领取！'); break;
                case "上架":this.toDeleteFn(data,'确认要上架这款耗材吗？'); break;
                case "补充数量": this.addNumFn(data);break;
                case "请确认": 
                    this.$refs.confirmDialog.dialogTitle = '耗材领用确认'
                    this.$refs.confirmDialog.this_id = data.id
                    this.$refs.confirmDialog.dialogVisible = true
                    this.$refs.confirmDialog.textList = [
                        `申请人：${data.user_name}`,
                        `所属部门：${data.dept_name}`,
                        `耗材名称：${data.c_name}`,
                        `耗材编码：${data.c_code}`,
                        `领用数量：${data.re_num}`,
                        `请确认耗材已经交付给申请人！`
                    ];break;
                ;break;
            }
        },
        /**补充数量 */
        addNumFn(val){
            this.ruleForm.formList = [
                {type:'text',label:'耗材名称',formValue:val.c_name},
                {type:'text',label:'耗材编码',formValue:val.c_code},
                {type:'text',label:'计量单位',formValue:val.c_unit},
                { type: 'number', name:'c_stock', label: '补充数量', placeholder: '请输入补充数量',formValue:'',rules:[{ required: true, message: '请输入补充数量', trigger: 'blur' },{ type:'number', message: '请输入数字', trigger: 'blur' }]},
                { type: 'number', name:'c_unit_price', label: '单价', placeholder: '请输入单价',formValue:'',rules:[{ required: true, message: '请输入单价', trigger: 'blur' },{ type:'number', message: '请输入数字', trigger: 'blur' }]},
            ]
            this.ruleForm.addForm = [
                {name:'id',formValue:val.id},
            ]
            this.dialogVisible = true

        },
        /**表格CheckBox勾选事件 */
        handleSelectionChange(selection){
            this.selectionData = selection
            this.selectionLength = selection.length
            this.printIds = []
            selection.map(item=>{
                this.printIds.push(item.id)
            })
        },
        goConfirm(id){
            confirmConsumable({id:id}).then(res=>{
                this.messageSearch()
                this.getConsumable()
            })
        },
        /*t上下架或确定派发*/
        toDeleteFn(val,label){
            this.$confirm(`${label}`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // let promise = label=='确认发放这个耗材吗？'?confirmConsumable({id:val.id}):showConsumables({id:val.id,is_show:val.is_show==1?2:1})
                let promise = showConsumables({id:val.id,is_show:val.is_show==1?2:1})
                promise.then(res=>{
                    this.messageSearch()
                })
            })
        },
        /*操作列表分页传过来的 当前第几页 */
        currentChangeFn(val){
            this.paginationMes.current_page = val||1//当前页数
            this.messageSearch()
        },
        /*操作列表分页传过来的 table每页的条数*/
        sizeChangeFn(val){
            this.paginationMes.current_page=1
            this.paginationMes.per_page = val||10//当前页数
            this.messageSearch()
        },
        //耗材编号前往详情页面
        pointerClick(data){
            this.$router.push({name:"myAssetsDetails",query:{key:data.asset_id, param: this.$route.meta.title,}})
        },
        getConsumable() {
          getConsumableNumber({wh_id:this.form.wh_id}).then(res=>{
            this.$store.commit('changeConsumableNumber',res);
            this.tabArr = [
               {num: '',content:'耗材列表'},
			   {num: '',content:'耗材分类'},
			   {num: '',content:'新增耗材'},
			   {num: `${this.$store.state.consumableNumber.receive || 0}`,content:'领用申请'},
			   {num: '',content:'库存预警'}
			]
          })
        },
        
    }
}
</script>

<style lang='stylus' scoped>
.meterialManagement
    min-width 1300px
    .head_btn
        height 32px
        color #3296FA
        border 1px solid #3296FA 
    .operationBox
        background-color #fff
        padding 37px 40px
    .contentTitleBox
        height 32px 
        line-height 32px
        font-size 12px
        background rgba(50, 150, 250, 0.08)
        border-radius 4px
        padding 0 12px
        margin-bottom 10px
        font-family "SourceHanSansCN-Regular"
        span 
            font-family "SourceHanSansCN-Regular"
            color #3296FA 
            .el-button
                >>>span 
                    font-size 12px 
                    margin-left 10px
    

    .contentTableBox
        background #fff
        padding 20px 12px
        border-radius 4px
        .table_btn
            height 32px
            line-height 32px
            margin-bottom 12px
            .el-button
                height 32px
            .table_btn_right
                float right
    .recycleBinBox
        background #fff
        padding 20px 12px
        border-radius 4px

    
    .printSetupBox
        background #fff
        borber-radius 0 0 4px 4px
        padding 10px 12px 20px 
        margin-top -20px
        .printSetupList
            .print_item
                height 360px
                border-radius 4px
                border 1px solid #DCDFE6 
                overflow hidden
                margin 0 0 10px 0
                display flex
                justify-content center
        
        .printBtnList
            margin 30px 0 20px 0
            display flex
            .el-button
                width 100px
                height 32px
    .errorlist 
        margin-top 12px
        li
            line-height 30px
            color red
    .dialog-footer
        text-align: center;
</style>

